<template>
  <div class="app-container">
      <div class="ci">
          <div class="item">
            <span class="name required">教师名字</span>
            <span class="value">
              <el-input clearable v-model="teacherInfo.name" maxlength="10" placeholder="教师名字" style="width: 220px;"></el-input>
            </span>
          </div>
          <div class="item h100">
            <span class="name">教师图片</span>
            <span class="value pics publicitypic">
                <div class="pic" v-for="(item,index) in teacherInfo.pictrues" :key="index">
                  <bx-image :src="item" :width="80" :height="80" :show-delete="true" :index="index" @delete-handler="teacherPicDeleteHandle" @load-complete="pictrueLoaded"></bx-image>
               </div>
              <div class="upload-box" @click="clickUploadTeacherFile()" v-show="teacherInfo.pictrues.length==0">
                   <i class="el-icon-plus avatar-uploader-icon"></i>
                   <input ref="selectfileForCourse" type="file" style="display:none;" @change="selectFileTeacher($event)" />
                </div>
            </span>
          </div>
          <div class="item">
            <span class="name">任教机构</span>
            <span class="value">
                {{teacherInfo.shopName}}
            </span>
          </div>
          <div class="item">
            <span class="name required">教学经验</span>
            <span class="value">
              <el-input type="number" min="0" max="100"  v-model="teacherInfo.teachExp"  style="width: 130px;"></el-input>年
            </span>
          </div>
          <div class="item">
            <span class="name required">教学科目</span>
            <span class="value">
              <el-input clearable v-model="teacherInfo.subject" max="100" placeholder="教师所授学科目" style="width: 100%"></el-input>
            </span>
          </div>
          <div class="item h100">
            <span class="name required">教师简介</span>
            <span class="value">
              <el-input  type="textarea" :rows="4"  maxlength="200"  placeholder="写一段简短的教师介绍（少于200字）"  v-model="teacherInfo.introduce"></el-input>
            </span>
          </div>
          <div class="item  h100">
            <span class="name">教学成果</span>
            <span class="value">
              <el-input type="textarea" :rows="4"  maxlength="200" v-model="teacherInfo.achievement" placeholder="教师所取得的一些成果（少于200字）"></el-input>
            </span>
          </div>


          
          <div class="item">
            <span class="name"></span>
            <span class="value">
              <el-button type="primary" @click="savePageInfo()" :loading="saveloading">保存</el-button>
            </span>
          </div>
          <!--- end -->
      </div>
  </div>
</template>

<script>
import path from 'path'
import { deepClone,parseTime } from '@/utils'
import * as auth from '@/utils/auth'
import * as shopApi from '@/api/shop'
import * as uploadApi from '@/api/upload'
import draggable from 'vuedraggable'
import BxImage from '@/components/BxImage'
import guid from '@/utils/guid'
import * as imageHelper from '@/utils/image'
import * as fileUpload from '@/utils/fileupload'
//import * as qiniu from 'qiniu-js'

const defaultRole = {
  key: '',
  name: '',
  description: '',
  routes: []
}

export default {
  name:'TeacherDetails',
  components: {
    draggable,
    BxImage
  },
  data() {
    return {
      saveloading:false,
      teacherInfo:{
        id:guid.empty,
        name:'',
        shopName:'',
        pictrues:[],
        pictruesOrigin:[],
        teachExp:'',
        subject:'',
        introduce:'',
        achievement:''
      },
      
      upload:{
        token:'',
        pictrues:{
          running:false,
          percent:0,
          state:0,
          previewing:false
        }
      }
    }
  },
  computed: {
    
  },
  created() {
    var that=this;
    const id = that.$route.params && that.$route.params.id
    const token=auth.getToken();

    if(id && id!='0'){
      shopApi.getTeacherInfo({id:id}).then(res=>{
         if(res.data){
            that.teacherInfo.id=res.data.id;
             that.teacherInfo.name=res.data.name;
             //that.teacherInfo.pictrues=[imageHelper.GetFullUrl(res.data.image,700,700)];
             that.teacherInfo.pictrues.push(imageHelper.GetFullUrl(res.data.image,700,700));
             that.teacherInfo.pictruesOrigin.push(res.data.image);
             
             that.teacherInfo.introduce=res.data.introduce || '';
             that.teacherInfo.teachExp=res.data.teachExp;
             that.teacherInfo.subject=res.data.subject || '';
             that.teacherInfo.achievement=res.data.achievement || '';
             
             shopApi.getShopInfo({id:res.data.shopId}).then(res2=>{
                that.teacherInfo.shopName=res2.data.shopName;
             })
             console.log(that.teacherInfo)
         }
      });
    }
    //加载上传token
    uploadApi.GetUploadToken(1).then(res=>{
        that.upload.token=res.data.token;
    });
    
  },
  methods: {
    
    //上传教师图片
    clickUploadTeacherFile(){
      var check=this.teacherInfo.pictrues.filter(function(item){return item!=''});
      //目前暂时只传一张图片
      if(check.length==1){ 
        this.$message({
          message: '请先移除要替换的图片',
          type: 'warning'
        });
        return;
      }
      if(this.upload.pictrues.running){
        this.$message({
          message: '当前正在上传中',
          type: 'warning'
        });
        return;
      }
      this.$refs.selectfileForCourse.dispatchEvent(new MouseEvent('click'))
    },
    selectFileTeacher($event){
      var that=this;
      var token=that.upload.token;
      var key=guid.createGuid().replace(/-/g,'').replace(/-/g,'')+".jpg";

       var files=$event.target.files;
       if(files.length==0){return;}
       that.upload.pictrues.running=true;
       that.upload.pictrues.percent=0;

       fileUpload.uploadQiniu({
          file:files[0],
          token:token,
          key:key,
          process:function(percert){
            console.log('正在上传...'+percert.toFixed(2)+'%');
          }
       }).then(completeres=>{
          console.log("上传成功",completeres);
          that.upload.pictrues.state=2;
          that.upload.pictrues.running=false;
          that.teacherInfo.pictrues.push(imageHelper.GetFullUrl(completeres.key,200,200))
          that.teacherInfo.pictruesOrigin.push(completeres.key);
          that.upload.pictrues.state=1;
          that.upload.pictrues.previewing=true;
          that.upload.pictrues.percent=100;
          setTimeout(function(){
              that.upload.pictrues.running=false;
            },1000)
       }).catch(err=>{
         that.upload.pictrues.running=false;
          that.$message({
            message: err,
            type: 'danger'
          });
       })
    },
    //删除图片
    teacherPicDeleteHandle(index){

       //this.$set(this.teacherInfo.pictrues,index, '')
       
       this.teacherInfo.pictrues.splice(index,1);
       this.teacherInfo.pictruesOrigin.splice(index,1);
       this.$refs.selectfileForCourse.value='';
       
    },
    pictrueLoaded(resultObj){
      //如果图片加载失败，则把占位符去掉（把该图片删除）
      if(!resultObj.result){
          this.teacherPicDeleteHandle(resultObj.index);
      }
    },

    //保存
    savePageInfo(){
      var that=this;
      var errorMsg=[];
      if(that.teacherInfo.name.trim().length==0){
        errorMsg.push('请填写教师名字');
      }

      // if(that.teacherInfo.pictruesOrigin.length==0){
      //   errorMsg.push('请上传教师图片');
      // }
      if(that.teacherInfo.teachExp==0){
        errorMsg.push('请填写教师年限');
      }
      if(!that.teacherInfo.subject.trim()){
        errorMsg.push('请填写教学科目');
      }
      if(!that.teacherInfo.introduce.trim()){
        errorMsg.push('请填写教师简介');
      }

      if(errorMsg.length>0){
        var errorHtml='<p class="errorbox-item">'+errorMsg.join('</p><p class="errorbox-item">')+'</p>';
        that.$notify({
          title: '验证未通过',
          dangerouslyUseHTMLString: true,
          position: 'bottom-left',
          message: errorHtml
        });
        return;
      }
      var data={
        "id":that.teacherInfo.id,
        "image": that.teacherInfo.pictruesOrigin.join(','),
        "name": that.teacherInfo.name,
        "teachExp": that.teacherInfo.teachExp,
        "subject": that.teacherInfo.subject,
        "introduce": that.teacherInfo.introduce,
        "achievement": that.teacherInfo.achievement,
        
      };
      that.saveloading=true;
      shopApi.saveTeacherInfo(data).then(res=>{
        if(res.data){
          that.$message({
            message: '保存成功！',
            type: 'success'
          });
          
          setTimeout(()=>{
            that.saveloading=false;
          },500)
        }else{
          that.saveloading=false;
        }
      }).catch(()=>{
        that.saveloading=false;
      })
    }
  }
}
</script>


